package com.example.hyznbk.view.adapter;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.andview.refreshview.recyclerview.BaseRecyclerAdapter;
import com.example.hyznbk.R;
import com.example.hyznbk.model.result.DifficultReviewEntity;
import com.example.hyznbk.utils.AnimatorHelper;
import com.example.hyznbk.utils.TextUtils;
import com.example.hyznbk.view.widget.RatingBar;
import com.example.hyznbk.view.widget.RippleView;
import com.lancoo.reviewsystem.utils.DensityUtils;
import com.lancoo.reviewsystem.utils.TimeUtils;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by tangminglong on 17/7/29.
 */

public class DifficultReviewAdapter extends BaseRecyclerAdapter<DifficultReviewAdapter.ViewHolder> {

    private List<DifficultReviewEntity.ImpAndDifTutorBean> mList;
    private Context mContext;
   // Map<String,String> fillMap = new HashMap<>();
    //Map<String,String> radioMap = new HashMap<>();
   // String fillIds;
    //String radioIds;

    private OnItemClickListener onItemClickListener;
    private int mLastPosition = -1;


    public DifficultReviewAdapter(Context mContext) {
        this.mContext = mContext;
        mList = new ArrayList<>();
        initQuesType();
    }

    public DifficultReviewAdapter(List<DifficultReviewEntity.ImpAndDifTutorBean> mList, Context mContext) {
        this.mList = mList;
        this.mContext = mContext;
        initQuesType();
    }

    public  interface OnItemClickListener{
        void onItemClick(View view, List<DifficultReviewEntity.ImpAndDifTutorBean> list, int position);

    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }


    private void initQuesType(){

       /* String[] typeArrays = mContext.getResources().getStringArray(R.array.QuesType_TWO_Arrays);
        radioIds = typeArrays[0];
        fillIds = typeArrays[1];*/
    }

    @Override
    public ViewHolder getViewHolder(View view) {
        return new ViewHolder(view,false);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_difficult_review, parent, false);
        return new ViewHolder(view,true);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position, boolean isItem) {
        holder.rippleLayout.setTag(position);

        holder.rippleLayout.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override
            public void onComplete(RippleView v) {
                if ( mList.size() != 0) {
                    if (onItemClickListener != null){
                        onItemClickListener.onItemClick(v,mList, (Integer) v.getTag());
                    }
                }

            }
        });

       /* holder.continueAnswer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // ToastUtils.showShort("第"+(position+1)+"个");
              if (onItemClickListener != null){
                  onItemClickListener.onItemClick(v,mList, (Integer) v.getTag());
              }
            }
        });*/


        DifficultReviewEntity.ImpAndDifTutorBean infoBean = mList.get(position);

        if (infoBean.getState() == 0){//未作答
            holder.continueAnswer.setText(mContext.getString(R.string.begin_answer));
        }else if (infoBean.getState() == 1){//作答中
            holder.continueAnswer.setText(mContext.getString(R.string.continue_answer));
        }else if (infoBean.getState() == 2){ //已提交
            holder.continueAnswer.setText(mContext.getString(R.string.look_answer));
        }

        if (infoBean.getState() == 2){ //已完成
            holder.linearLayout.setBackgroundResource(R.mipmap.bg_item_fill);
            Drawable fullDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_full_green);
            fullDraw.setBounds(0,0,fullDraw.getIntrinsicWidth(),fullDraw.getIntrinsicHeight());
            Drawable halfDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_half_green);
            halfDraw.setBounds(0,0,halfDraw.getIntrinsicWidth(),halfDraw.getIntrinsicHeight());
            Drawable emptyDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_empty_green);
            halfDraw.setBounds(0,0,emptyDraw.getIntrinsicWidth(),emptyDraw.getIntrinsicHeight());
            holder.ratingBar.setStarHalfDrawable(halfDraw);
            holder.ratingBar.setStarFillDrawable(fullDraw);
            holder.ratingBar.setStarEmptyDrawable(emptyDraw);
            holder.continueAnswer.setBackgroundResource(R.mipmap.bg_btn_green);
            holder.imgQuesType.setImageResource(R.mipmap.bg_label_fill);
            holder.tvQuesType.setTextColor(ContextCompat.getColor(mContext,R.color.item_difficult_text_green));
            Drawable drawable = ContextCompat.getDrawable(mContext,R.drawable.progressbar_bar_drawable_green);
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
            holder.progressBar.setProgressDrawable(drawable);

            Date updateTime = mList.get(position).getUpdateTime();
            holder.paperLastAnswerTime.setText(TimeUtils.getDate(updateTime));
        }else { //
            holder.linearLayout.setBackgroundResource(R.mipmap.bg_item_radio);
            Drawable fullDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_full);
            fullDraw.setBounds(0,0,fullDraw.getIntrinsicWidth(),fullDraw.getIntrinsicHeight());
            Drawable halfDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_half);
            halfDraw.setBounds(0,0,halfDraw.getIntrinsicWidth(),halfDraw.getIntrinsicHeight());
            Drawable emptyDraw = ContextCompat.getDrawable(mContext,R.mipmap.ic_star_empty);
            halfDraw.setBounds(0,0,emptyDraw.getIntrinsicWidth(),emptyDraw.getIntrinsicHeight());
            holder.ratingBar.setStarHalfDrawable(halfDraw);
            holder.ratingBar.setStarFillDrawable(fullDraw);
            holder.ratingBar.setStarEmptyDrawable(emptyDraw);
            holder.continueAnswer.setBackgroundResource(R.mipmap.bg_btn_blue);
            holder.imgQuesType.setImageResource(R.mipmap.bg_label_radio);
            holder.tvQuesType.setTextColor(ContextCompat.getColor(mContext,R.color.item_difficult_text_blue));
            Drawable drawable = ContextCompat.getDrawable(mContext,R.drawable.progressbar_bar_drawable_blue);
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
            holder.progressBar.setProgressDrawable(drawable);

            holder.paperLastAnswerTime.setText(mContext.getString(R.string.no_answered));
        }
        TextUtils.adjustTvTextSize(holder.tvQuesType,
                DensityUtils.dp2px(mContext,40),infoBean.getTypeName());




        int finishedCount = mList.get(position).getAnsweredItemCount();
        int totalCount = mList.get(position).getTotalItemCount();

        //String lastAnswerTime = String.format(mContext.getString(R.string.paper_lastAnswerTime),);

        holder.paperInduction.setText(Html.fromHtml(infoBean.getQuesBrief()));


        float finishedPercent = (float) Math.floor((float)finishedCount / totalCount * 100) / 100;
       // float finishedPercent = (float)finishedCount / totalCount;
        NumberFormat format = NumberFormat.getPercentInstance();// 获取格式化类实例 带百分比
        format.setMinimumFractionDigits(0);// 设置小数位
        holder.paperFinishPercent.setText("已作答"+ format.format(finishedPercent));

        holder.progressBar.setProgress((int)(finishedPercent*100));

        holder.ratingBar.setStar(infoBean.getDifficulty());
        int adapterPosition = holder.getAdapterPosition();

        boolean isScrollDown = adapterPosition > mLastPosition;

        for (Animator anim : AnimatorHelper.getRecyclerAnimator(holder.itemView,isScrollDown)) {
            anim.start();
        }
        mLastPosition = adapterPosition;

    }

    @Override
    public int getAdapterItemCount() {
        return mList.size();
    }

    public void add(List<DifficultReviewEntity.ImpAndDifTutorBean> entityList) {
        int startPosition = getStart()+getAdapterItemCount();
        mList.addAll(entityList);
        notifyItemRangeInserted(startPosition,entityList.size());
    }

    public void clearAndAdd(List<DifficultReviewEntity.ImpAndDifTutorBean> entityList){
        mLastPosition = -1;
        mList.clear();
        mList.addAll(entityList);
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView paperLastAnswerTime;
        private RippleView rippleLayout;
        private LinearLayout linearLayout;
        private TextView paperInduction;//资料简介
        private TextView paperFinishPercent;//资料完成度
        private ProgressBar progressBar;//资料进度显示
        private RatingBar ratingBar;
        private TextView continueAnswer;
        private ImageView imgQuesType;
        private TextView tvQuesType;

        public ViewHolder(View itemView,boolean isItem) {
            super(itemView);
            if (isItem){
                rippleLayout = (RippleView) itemView.findViewById(R.id.item_ripper);
                linearLayout = (LinearLayout) itemView.findViewById(R.id.item_liner);
                paperInduction = (TextView) itemView.findViewById(R.id.tv_paperSummary);
                paperLastAnswerTime = (TextView) itemView.findViewById(R.id.tv_time);
                paperFinishPercent = (TextView) itemView.findViewById(R.id.tv_finishedPercent);
                progressBar = (ProgressBar) itemView.findViewById(R.id.pb_finished);
                ratingBar = (RatingBar) itemView.findViewById(R.id.rb_hval);
                continueAnswer = (TextView) itemView.findViewById(R.id.tv_continueAnswer);
                imgQuesType = (ImageView) itemView.findViewById(R.id.img_quesType);
                tvQuesType = (TextView) itemView.findViewById(R.id.tv_quesType);




            }
        }
    }




    public void setMaxEcplise(final TextView mTextView, final int maxLines, final String content) {

        ViewTreeObserver observer = mTextView.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mTextView.setText(Html.fromHtml(content));
                if (mTextView.getLineCount() > maxLines) {
                    int lineEndIndex = mTextView.getLayout().getLineEnd(maxLines - 1);
                    //下面这句代码中：我在项目中用数字3发现效果不好，改成1了
                    String text = content.subSequence(0, lineEndIndex - 3) + "...";
                    mTextView.setText(text);
                }
                else {
                    removeGlobalOnLayoutListener(mTextView.getViewTreeObserver(), this);
                }
            }
        });
    }

    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    private void removeGlobalOnLayoutListener(ViewTreeObserver obs, ViewTreeObserver.OnGlobalLayoutListener listener) {
        if (obs == null)
            return;
        if (Build.VERSION.SDK_INT < 16) {
            obs.removeGlobalOnLayoutListener(listener);
        }
        else {
            obs.removeOnGlobalLayoutListener(listener);
        }
    }


}
